package com.jdbc;

import java.sql.*;
import java.util.Scanner;

/**
 * 登录案例
 */
public class LoginDemo {

    public static final String URL = "jdbc:mysql://localhost:3306/mydb?serverTimezone=GMT&useUnicode=true&characterEncoding=UTF-8";
    public static final String USER = "root";
    public static final String PASSWORD = "123456";
    /**
     * 登录方法
     */
    public static boolean login(String username,String password){
        // 1.获取连接
        try(Connection connection = DriverManager.getConnection(URL,USER,PASSWORD)){
            // 2.定义sql
            String sql = "select * from t_user where username = '"+ username +"' and password = '"+ password +"'";
            // 3.获得命令对象
            Statement statement = connection.createStatement();
            // 4.执行查询命令
            ResultSet resultSet = statement.executeQuery(sql);
            // 5.判断是否有匹配的账号密码
            if(resultSet.next()){
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 登录方法
     */
    public static boolean login2(String username,String password){
        // 1.获取连接
        try(Connection connection = DriverManager.getConnection(URL,USER,PASSWORD)){
            // 2.定义sql
            String sql = "select * from t_user where username = ? and password = ?";
            // 3.获得命令对象
            PreparedStatement statement = connection.prepareStatement(sql);
            // 4.设置参数
            statement.setString(1,username);
            statement.setString(2,password);
            // 5.执行查询命令
            ResultSet resultSet = statement.executeQuery();
            // 6.判断是否有匹配的账号密码
            if(resultSet.next()){
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = scanner.nextLine();
        System.out.println("请输入密码：");
        String password = scanner.nextLine();
        if(login2(username,password)){
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }
    }
}
